<?php

namespace app\admin\controller\formdesign;

use addons\formdesign\library\Formdesign;
use addons\formdesign\library\FormDesignApi;
use addons\formdesign\library\Formsafe;
use app\common\controller\Backend;

/**
 * 表单管理
 *
 * @icon fa fa-circle-o
 */
class Form extends Backend
{

    /**
     * Form模型对象
     * @var \app\common\model\formdesign\Form
     */
    protected $model = null;
    protected $noNeedLogin = []; //无需登录的方法,同时也就不需要鉴权了
    protected $noNeedRight = []; //无需鉴权的方法,但需要登录
    protected $dataLimit = 'personal'; //默认基类中为false，表示不启用，可额外使用auth和personal两个值
    protected $dataLimitField = 'admin_id'; //数据关联字段,当前控制器对应的模型表中必须存在该字段

    public function _initialize()
    {
        parent::_initialize();
        $config = get_addon_config('formdesign');
        $this->dataLimit = $config['dataLimit'];
        $this->dataLimitField = $config['dataLimitField'];
        $this->model = model('app\common\model\formdesign\Form');
        $this->view->assign("statusList", $this->model->getStatusList());
        Formsafe::safe_gpc();
    }

    public function list()
    {
        $this->request->filter(['strip_tags', 'trim']);
      
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
        }
    }
    /**
     * 用于构建组件
     */
    public function buildPlugins()
    {
        $params = $this->request->param();
        $formdesign = new Formdesign();
        $plugins = $formdesign->buildPlugins($params);
        if ($this->request->isAjax()) {
            $this->success("", null, $plugins);
        } else {
            return $plugins;
        }
    }

    /**
     * 打开组件设置页面
     */
    public function settings()
    {
        $type = trim($this->request->param('type'));
        $params = $this->request->param();
        $this->view->engine->layout('formdesign/layout/default');
        $this->assign('params', $params);
        return $this->view->fetch('./assets/addons/formdesign/settings/' . $type . '.html');
    }

    /**
     * 表单设计页面
     */
    public function drag()
    {
        $form_id = $this->request->param('ids');

        if ($form_id <= 0) {
            $this->error('参数有误，请返回重试!');
        }
        $map = array(
            'id' => $form_id,
            'status' => 'normal',
        );
        $form = $this->model->where($map)->find();
        if (!$form) {
            $this->error('未找到表单数据，请返回重试!');
        }
        if ($this->request->isAjax()) {
            $design_content = trim($this->request->post('design_content'));
            if ($design_content !== '') {
                $layout = $this->request->post('layout');
                $formdesign = new Formdesign();
                $parse_content = $formdesign->parse_form($design_content, $form['fields']);
                $design_content = $parse_content['template'];
                $formdesign->parse_table($form_id, $parse_content['add_fields']); //创建表或添加字段
                $data = array(
                    'id' => $form_id,
                    'layout' => $layout,
                    'fields' => $parse_content['fields'],
                    'content' => $parse_content['template'],
                    'content_data' => serialize($parse_content['data']),
                );
                $map = array(
                    'id' => $form_id,
                );
                $trans = $this->model->allowField(true)->where($map)->update($data);

                if (!$trans) {
                    $this->error('保存失败,请重试！');
                }
                $this->success('保存成功！');
            } else {
                $this->error('表单不能为空！');
            }
        }

        $formdesign = new Formdesign();
        $form['content'] = $formdesign->unparse_form($form, [], 'design');
        $this->assign('one', $form);
        return $this->view->fetch();
    }

    /**
     * 临时预览页面
     */
    public function tempview()
    {
        $form_id = $this->request->param('form_id');
        $layout = $this->request->param('layout');
        $form = $this->model->get($form_id);
        $temp['content'] = $this->request->param('design_content');
        if ($temp !== '' or $temp !== ' ') {
            $formdesign = new Formdesign();
            $design_content = $formdesign->unparse_form($temp, [], 'preview');
            $this->assign('design_content', $design_content);
            $this->assign('layout', $layout);
            $this->view->engine->layout('layout/default');
        } else {
            $this->error('表单不能为空！');
        }
        return $this->view->fetch();
    }
    /**
     * 表单预览页面
     */
    public function preview()
    {
        $form_id = $this->request->param('ids');
        if ($form_id <= 0) {
            $this->error('参数有误，请返回重试!');
        }
        $map = array(
            'id' => $form_id,
            'status' => 'normal',
        );
        $form = $this->model->where($map)->find();

        if (!$form) {
            $this->error('未找到表单数据，请返回重试!');
        }

        $formdesign = new Formdesign();
        $form['content'] = $formdesign->unparse_form($form, array(), 'preview');

        $this->assign('one', $form);
        $this->view->engine->layout('layout/default');
        return $this->view->fetch();
    }
    /**
     * 表单删除及数据删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $FormDesign = new FormDesignApi($v['id']);
                $count += $FormDesign->destroy();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
